/**
 * 文件上传
 * @param {*} file File
 * @param {*} param 上传前请求的参数
 * @param {*} successCallback 上传成功
 * @param {*} errorCallback 上传失败
 * @param {*} progressCallback 上传进度
 * @returns XMLHttpRequest，可用于取消上传
 */
export const uploadFile = async (
  file,
  param,
  successCallback,
  errorCallback,
  progressCallback?
) => {
  let xhr: any = null;
  if (window.ActiveXObject) {
    //IE浏览器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } else if (window.XMLHttpRequest) {
    //非IE浏览器
    xhr = new XMLHttpRequest();
  }
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      if (successCallback) {
        successCallback(file);
      }
    }
    if (xhr.readyState === 4 && xhr.status !== 200) {
      if (errorCallback) {
        errorCallback(file);
      }
    }
  };
  xhr.upload.addEventListener(
    "progress",
    function (event) {
      if (event.lengthComputable) {
        const rate = Math.ceil((event.loaded / event.total) * 100000) / 100000;
        if (progressCallback) {
          progressCallback({ file, rate, size: rate * file.size }, xhr);
        }
      }
    },
    false
  );

  const res = await readFile(file, param, xhr);
  return res;
};

export const readFile = async (file, param, xhr) => {
  return await new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function (e) {
      if (param.url.startsWith("http://")) {
        xhr.open("PUT", param.url.replace("http://", "https://"));
      } else {
        xhr.open("PUT", param.url);
      }
      xhr.setRequestHeader("Content-Type", param.contentType);
      if (xhr.sendAsBinary) {
        xhr.sendAsBinary(reader.result);
      } else {
        xhr.send(reader.result);
      }
      resolve(xhr);
    };
    reader.onerror = function (err) {
      reject(err);
    };
  });
};

/**
 * 下载文件
 * @param {*} link 文件url
 * @param {*} name 文件名称
 */
export const downloadFile = (link, name) => {
  // if (window.open) {
  //   window.open(link);
  // } else {
  if (link.startsWith("http://")) {
    link = link.replace("http://", "https://");
  }
  var x = new XMLHttpRequest();
  x.open("GET", link, true);
  x.responseType = "blob";
  x.onload = (e) => {
    var url = window.URL.createObjectURL(x.response);
    var a = document.createElement("a");
    a.setAttribute("target", "_blank");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.click();
  };
  x.send();
  // }
};
